package com.btex.app.pager;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.btex.app.Config;
import com.btex.app.LoginActivity;
import com.btex.app.R;
import com.btex.app.TradeActivity;
import com.btex.app.adapter.UsdtFragmentAdapter;
import com.btex.app.entity.MakeListInfo;
import com.btex.app.tools.CookieTool;
import com.btex.app.tools.MicroAVLIDialog;
import com.btex.app.tools.SharedPreferencesUtil;
import com.btex.app.tools.Util;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author zy zhangyi <zhangyi, 1104745049@QQ.com
 * @version v1.0
 * @project study1
 * @Description
 * @encoding UTF-8
 * @date 2018/5/18
 * @time 下午12:32
 * @修改记录 <pre>
 * 版本       修改人         修改时间         修改内容描述
 * --------------------------------------------------
 * <p>
 * --------------------------------------------------
 * </pre>
 */

public class UsdtFragment extends Fragment implements BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.fragmnet_first)
    RecyclerView mFragmnetFirst;
    Unbinder unbinder;
    @BindView(R.id.fragment_tv_type)
    TextView mFragmentTvType;
    @BindView(R.id.fragment_imag_type_first)
    ImageView mFragmentImagTypeFirst;
    @BindView(R.id.fragment_lin_type_first)
    LinearLayout mFragmentLinTypeFirst;
    @BindView(R.id.fragment_imag_zuixin_first)
    ImageView mFragmentImagZuixinFirst;
    @BindView(R.id.fragment_lin_zuixin_first)
    LinearLayout mFragmentLinZuixinFirst;
    @BindView(R.id.fragment_imag_zhangdie_first)
    ImageView mFragmentImagZhangdieFirst;
    @BindView(R.id.fragment_lin_zhangdie_first)
    LinearLayout mFragmentLinZhangdieFirst;
    private UsdtFragmentAdapter mBtcFragmentAdapter;
    private List<MakeListInfo.DataBean.USDTBean> mBtc;

    public boolean isChengjiao = false;
    public boolean isChecket = false;
    public boolean isChecketJia = false;
    public boolean isNew = false;

    private SharedPreferencesUtil sp;
    private PreferencesCookieStore cookieStore;
    private boolean mIsVisibleToUser;


    public static Fragment newInstance() {
        UsdtFragment fragment = new UsdtFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment_layout, null);
        unbinder = ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        sp = SharedPreferencesUtil.getSharedPreferences(getActivity());
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initRecyclerview();


    }

    private void initRecyclerview() {
        mFragmnetFirst.setLayoutManager(new LinearLayoutManager(getActivity()));
        mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
        mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
        mBtcFragmentAdapter.setOnItemClickListener(this);
        mBtcFragmentAdapter.setOnItemChildClickListener(this);

    }


    @Override
    public void onResume() {
        super.onResume();
        initRecyclerview();
        getMakeListInfo();
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 0);
    }

    public void getMakeListInfo() {

        PreferencesCookieStore cookieStore = CookieTool.getCookieStore(getActivity(), sp);

        int num = (int) ((Math.random() * 9 + 1) * 100000);

        OkGo.<String>get(Config.GET_MARKET_LISTS + "?rnd=" + String.valueOf(num)).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String result = response.body();
                Log.i("nbvcnxmfghjdk===USDT", result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
                        Gson gson = new Gson();
                        MakeListInfo makeListInfo = gson.fromJson(result, MakeListInfo.class);
                        mBtc = makeListInfo.getData().getUSDT();

                        if (mBtc != null) {

                            if (mFragmnetFirst != null && mBtcFragmentAdapter != null) {

//                                mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                                mBtcFragmentAdapter.setNewData(mBtc);
                            }
                        } else {
                            if (mFragmnetFirst != null && mBtcFragmentAdapter != null) {
                                mBtcFragmentAdapter.setEmptyView(R.layout.empty, mFragmnetFirst);
                                mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                            }
                        }

                    }
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        });

//        new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.GET, Config.GET_MARKET_LISTS + "?rnd=" + String.valueOf(num), new RequestCallBack<String>() {
//            @Override
//            public void onSuccess(ResponseInfo<String> responseInfo) {
//
//                String result = responseInfo.result;
//                Log.i("nbvcnxmfghjdk===USDT", result);
//                try {
//                    JSONObject jsonObject = new JSONObject(result);
//                    if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                        Gson gson = new Gson();
//                        MakeListInfo makeListInfo = gson.fromJson(result, MakeListInfo.class);
//                        mBtc = makeListInfo.getData().getUSDT();
//
//                        if (mBtc != null) {
//
//                            if (mFragmnetFirst != null && mBtcFragmentAdapter != null) {
//
////                                mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
//                                mBtcFragmentAdapter.setNewData(mBtc);
//                            }
//                        } else {
//                            if (mFragmnetFirst != null && mBtcFragmentAdapter != null) {
//                                mBtcFragmentAdapter.setEmptyView(R.layout.empty, mFragmnetFirst);
//                                mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
//                            }
//                        }
//
//                    }
//                } catch (JSONException e) {
//                    e.printStackTrace();
//
//                }
//
//            }
//
//            @Override
//            public void onFailure(HttpException error, String msg) {
//
//
//            }
//        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Subscribe
    public void onEvent(String event) {

        if (event.equals("chengjiao")) {

            mFragmentTvType.setText("成交量");

        } else if (event.equals("zhangdie")) {

            mFragmentTvType.setText("涨跌幅");
        }
        if (mBtcFragmentAdapter != null) {
            mBtcFragmentAdapter.notifyDataSetChanged();
        }


    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

        MakeListInfo.DataBean.USDTBean usdtBean = (MakeListInfo.DataBean.USDTBean) adapter.getData().get(position);
        String pair = usdtBean.getPair();
        Intent intent = new Intent(getActivity(), TradeActivity.class);
        intent.putExtra("pair", pair);
        startActivity(intent);


    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {


        boolean isEngilsh = sp.getBoolean(Config.KEY_IS_LOGIN, false);

        if (!isEngilsh) {

            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);

        } else {


            cookieStore = CookieTool.getCookieStore(getActivity(), sp);
            MakeListInfo.DataBean.USDTBean usdtBean = (MakeListInfo.DataBean.USDTBean) adapter.getData().get(position);
            String id = usdtBean.getId();
            int collect_id = usdtBean.getCollect_id();

            if (collect_id > 0) {


                RequestParams params = new RequestParams();
                params.addBodyParameter("collect_id", String.valueOf(collect_id));
                params.addHeader("myclient", "android");


                final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
                microAVLIDialog.show();

                new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.DEl_COLLECT, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        if (microAVLIDialog != null) {
                            microAVLIDialog.dismiss();
                        }

                        String result = responseInfo.result;
                        try {
                            JSONObject jsonObject = new JSONObject(result);

                            if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                                Toast.makeText(getActivity(), R.string.del_info, Toast.LENGTH_SHORT).show();
//                                Snackbar snackbar = Util.ShortSnackbar(mFragmentImagTypeFirst, getString(R.string.del_info), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                                snackbar.show();
                                Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), getString(R.string.del_info));
                                getMakeListInfo();
//                                microAVLIDialog.dismiss();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {


                    }
                });


            } else {


                RequestParams params = new RequestParams();
                params.addBodyParameter("id", id);
                params.addHeader("myclient", "android");

                final MicroAVLIDialog microAVLIDialog = new MicroAVLIDialog(getActivity());
                microAVLIDialog.show();

                new HttpUtils().configCookieStore(cookieStore).send(HttpRequest.HttpMethod.POST, Config.COLLECT, params, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {

                        if (microAVLIDialog != null) {
                            microAVLIDialog.dismiss();
                        }

                        String result = responseInfo.result;
                        try {
                            JSONObject jsonObject = new JSONObject(result);

                            if ("1".equals(jsonObject.getString(Config.KEY_CODE))) {
//                                Toast.makeText(getActivity(), R.string.collect_suess, Toast.LENGTH_SHORT).show();
                                Util.showSnachBar(getActivity(), getResources().getColor(R.color.bg_green), getString(R.string.collect_suess));
//                                Snackbar snackbar = Util.ShortSnackbar(mFragmentImagTypeFirst, getString(R.string.collect_suess), Color.parseColor("#ffffff"), Color.parseColor("#272736"));
//                                snackbar.show();
//                                microAVLIDialog.dismiss();
                                getMakeListInfo();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();

                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {


                    }
                });

            }

            EventBus.getDefault().post("shoucang");

        }
    }

    @OnClick({R.id.fragment_lin_type_first, R.id.fragment_lin_zuixin_first, R.id.fragment_lin_zhangdie_first})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.fragment_lin_type_first:
                break;
            case R.id.fragment_lin_zuixin_first:

                if (mBtc == null) {
                    return;
                }

                if (isNew) {
                    mFragmentImagZuixinFirst.setBackground(getResources().getDrawable(R.mipmap.jian_xia));

                    Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                        @Override
                        public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();
                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);
                            if (v > v1) {
                                return 1;
                            } else if (v < v1) {
                                return -1;
                            } else {
                                return 0;
                            }

                        }
                    });

//                    mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                    mBtcFragmentAdapter.setOnItemClickListener(this);
                    mBtcFragmentAdapter.setOnItemChildClickListener(this);
                    mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                    mBtcFragmentAdapter.setNewData(mBtc);
                    isNew = !isNew;

                } else {
                    mFragmentImagZuixinFirst.setBackground(getResources().getDrawable(R.mipmap.jian_shang));
                    Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                        @Override
                        public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                            String zhangdie = ethBean.getTicker().getTrade_price();
                            String zhangdie1 = t1.getTicker().getTrade_price();

                            Double v = Double.valueOf(zhangdie);
                            Double v1 = Double.valueOf(zhangdie1);


                            if (v > v1) {
                                return -1;
                            } else if (v < v1) {
                                return 1;
                            } else {
                                return 0;
                            }

                        }
                    });

//                    mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                    mBtcFragmentAdapter.setOnItemClickListener(this);
                    mBtcFragmentAdapter.setOnItemChildClickListener(this);
                    mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                    mBtcFragmentAdapter.setNewData(mBtc);
                    isNew = !isNew;
                }

                break;
            case R.id.fragment_lin_zhangdie_first:


                if (mBtc == null) {
                    return;
                }

//                按成交价排序
                if (isChengjiao) {

                    if (isChecket) {

                        mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_xia));
//                        从低到高
                        Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                            @Override
                            public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                                String zhangdie = ethBean.getTicker().getTrade_price();
                                String zhangdie1 = t1.getTicker().getTrade_price();
                                Double v = Double.valueOf(zhangdie);
                                Double v1 = Double.valueOf(zhangdie1);
                                if (v > v1) {
                                    return 1;
                                } else if (v < v1) {
                                    return -1;
                                } else {
                                    return 0;
                                }

                            }
                        });

//                        mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                        mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                        mBtcFragmentAdapter.setOnItemClickListener(this);
                        mBtcFragmentAdapter.setOnItemChildClickListener(this);
                        mBtcFragmentAdapter.setNewData(mBtc);
                        isChecket = !isChecket;
                    } else {
//                        从高到低
                        mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_shang));


                        Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                            @Override
                            public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                                String zhangdie = ethBean.getTicker().getTrade_price();
                                String zhangdie1 = t1.getTicker().getTrade_price();

                                Double v = Double.valueOf(zhangdie);
                                Double v1 = Double.valueOf(zhangdie1);


                                if (v > v1) {
                                    return -1;
                                } else if (v < v1) {
                                    return 1;
                                } else {
                                    return 0;
                                }

                            }
                        });

//                        mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                        mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                        mBtcFragmentAdapter.setOnItemClickListener(this);
                        mBtcFragmentAdapter.setOnItemChildClickListener(this);
                        mBtcFragmentAdapter.setNewData(mBtc);
                        isChecket = !isChecket;
                    }


                } else {
//                    按涨跌幅排序


                    if (isChecketJia) {
                        //  从低到高
                        mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_xia));

                        Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                            @Override
                            public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                                String zhangdie = ethBean.getTicker().getChange_24h();
                                String zhangdie1 = t1.getTicker().getChange_24h();

                                Double v = Double.valueOf(zhangdie);
                                Double v1 = Double.valueOf(zhangdie1);


                                if (v > v1) {
                                    return 1;
                                } else if (v < v1) {
                                    return -1;
                                } else {
                                    return 0;
                                }

                            }
                        });

//                        mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                        mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                        mBtcFragmentAdapter.setOnItemClickListener(this);
                        mBtcFragmentAdapter.setOnItemChildClickListener(this);
                        mBtcFragmentAdapter.setNewData(mBtc);
                        isChecketJia = !isChecketJia;


                    } else {
//                        从高到低
                        mFragmentImagZhangdieFirst.setBackground(getResources().getDrawable(R.mipmap.jian_shang));

                        Collections.sort(mBtc, new Comparator<MakeListInfo.DataBean.USDTBean>() {
                            @Override
                            public int compare(MakeListInfo.DataBean.USDTBean ethBean, MakeListInfo.DataBean.USDTBean t1) {

                                String zhangdie = ethBean.getTicker().getChange_24h();
                                String zhangdie1 = t1.getTicker().getChange_24h();

                                Double v = Double.valueOf(zhangdie);
                                Double v1 = Double.valueOf(zhangdie1);

                                if (v > v1) {
                                    return -1;
                                } else if (v < v1) {
                                    return 1;
                                } else {
                                    return 0;
                                }

                            }
                        });

//                        mBtcFragmentAdapter = new UsdtFragmentAdapter(null);
                        mFragmnetFirst.setAdapter(mBtcFragmentAdapter);
                        mBtcFragmentAdapter.setOnItemClickListener(this);
                        mBtcFragmentAdapter.setOnItemChildClickListener(this);
                        mBtcFragmentAdapter.setNewData(mBtc);
                        isChecketJia = !isChecketJia;

                    }


                }


                break;
        }
    }

    private Handler handler = new Handler() {

    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (mIsVisibleToUser) {
                getMakeListInfo();
            }

            handler.postDelayed(this, 7000);
        }
    };


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {

        super.setUserVisibleHint(isVisibleToUser);

        mIsVisibleToUser = isVisibleToUser;
    }
}
